package service

import (
	"bytes"
	"encoding/json"
	"errors"
	"github.com/bgmp/config"
	log "github.com/sirupsen/logrus"
	"io/ioutil"
	"net/http"
)

func SportPredict(heartRate []int) (error, *SportPredictResponse) {
	url := config.GetSportPredictUrl()
	req := SportPredictRequest{HeartRate: heartRate}
	payload, err := json.Marshal(req)
	if err != nil {
		return err, nil
	}
	resp, err := http.Post(url, "application/json", bytes.NewBuffer(payload))
	if err != nil {
		log.Error("Error:", err)
		return err, nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		err = errors.New("无法进行运动预测")
		return err, nil
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Error("Error reading response body:", err)
		return err, nil
	}

	log.Info("Response Status:", resp.Status)

	rsp := SportPredictResponse{}
	err = json.Unmarshal(body, &rsp)
	if err != nil {
		return err, nil
	}
	return nil, &rsp
}

type SportPredictRequest struct {
	HeartRate []int `json:"heartRate"`
}

type SportPredictResponse struct {
	Energy string `json:"energy"`
}
